package com.shengzhe.ostudent.service.impl;

import com.shengzhe.ostudent.common.exception.OsException;
import com.shengzhe.ostudent.dao.RoleDao;
import com.shengzhe.ostudent.dao.impl.RoleDaoImpl;
import com.shengzhe.ostudent.entity.PageInfo;
import com.shengzhe.ostudent.entity.Role;
import com.shengzhe.ostudent.entity.RoleCondition;
import com.shengzhe.ostudent.entity.RoleTree;
import com.shengzhe.ostudent.service.RoleService;
import com.shengzhe.ostudent.utils.result.E;

import java.sql.SQLException;
import java.util.List;

public class RoleServiceImpl implements RoleService {
    private final RoleDao roleDao = new RoleDaoImpl();

    @Override
    public boolean add(Role role) throws SQLException {
//        if (role.getName() == null || role.getName().isEmpty()){
//            throw new OsException(E.REQUEST_CODE_N9);
//        }
//        if (role.getId() == null || role.getParentId() == 0){
//            role.setParentId(0L);
//            role.setLevel(1);
//        }else {
//            System.out.println("待增加的逻辑，需要查询父元素的level，在其基础上加1");
//        }
        if (role.getName() == null || role.getName().isEmpty()) {
            throw new OsException(E.REQUEST_CODE_N9);
        }
        if (role.getParentId() == null) {
            role.setParentId(0L);
            role.setLevel(1);
        } else if (role.getParentId() == 0) {
            role.setLevel(1);
        } else {
//            System.out.println("待加入的逻辑");
            //我们要现根据parentId找到父role，然后查找父亲role的level，待插入的role其level值为role的level值+1
            Role parentRole = roleDao.findById(role.getParentId());
            role.setLevel(parentRole.getLevel() + 1);
        }
        return roleDao.add(role) > 0;
    }

    @Override
    public Role findById(long id) throws SQLException {
        return roleDao.findById(id);
    }

    @Override
    public PageInfo<Role> displayRolePage(RoleCondition roleCondition) {
        return roleDao.displayRolePage(roleCondition);
    }

    @Override
    public RoleTree buildRoleTree(Role role) {
        RoleTree roleTree = new RoleTree();
        roleTree.setRole(role);
        List<Role> roleList = findChildren(role);
        for (Role roleChild : roleList) {
            roleTree.getTreeList().add(buildRoleTree(roleChild));
        }
        return roleTree;
    }

    public List<Role> findChildren(Role role) {
//        List<Role> list = new ArrayList<>();
//        List<Role> all = list();
//        for (Role roleChild : all) {
//            if (roleChild.getParentId() == role.getId()) {
//                list.add(roleChild);
//            }
//        }
        return roleDao.findChildren(role);
    }

    public List<Role> list(RoleCondition roleCondition) {
        return roleDao.list(roleCondition);
    }

    @Override
    public boolean modify(Role role) {
        return roleDao.modify(role);
    }

    @Override
    public boolean updateRole(Role role) {
        return roleDao.updateRole(role) > 0;
    }
}
